#include "adc_sew.h"

static int AdcConfigurationDone	= 1;

/**
Constructor
*/
ADC::ADC(uint8_t ADCchannel, uint8_t ADCsampleTime)
{
 	channel = ADCchannel;
	sampleTime =ADCsampleTime;
	ADCConfiguration();	
}

/**
ADC Configuration
*/
void ADC::ADCConfiguration()
{
	if(0 != AdcConfigurationDone)
	{
		//RCC configuration for temperature sensor on ADC channel 16
		RCC_ADCCLKConfig(RCC_PCLK2_Div2); 
	
	  ADC_InitTypeDef  ADC_InitStructure;
	  RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
	  ADC_DeInit(ADC1);
	  ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
	  ADC_InitStructure.ADC_ScanConvMode = DISABLE;
	  // Don't do contimuous conversions - do them on demand 
	  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
	  // Start conversin by software, not an external trigger 
	  ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
	  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	  // Say how many channels would be used by the sequencer 
	  ADC_InitStructure.ADC_NbrOfChannel = 1;
	
	  // Now do the setup
	  ADC_Init(ADC1, &ADC_InitStructure);
	  // Enable ADC1 
	  ADC_Cmd(ADC1, ENABLE);
		ADC_TempSensorVrefintCmd(ENABLE); 
	
	  // Enable ADC1 reset calibaration register 
	  ADC_ResetCalibration(ADC1);
	  // Check the end of ADC1 reset calibration register 
	  while(ADC_GetResetCalibrationStatus(ADC1));
	  // Start ADC1 calibaration 
	  ADC_StartCalibration(ADC1);
	  // Check the end of ADC1 calibration 
	  while(ADC_GetCalibrationStatus(ADC1));

		AdcConfigurationDone = 0;
		}
}

uint16_t ADC::readValue()
{
  ADC_RegularChannelConfig(ADC1, channel, 1, sampleTime );
  // Start the conversion
  ADC_SoftwareStartConvCmd(ADC1, ENABLE);
  // Wait until conversion completion
  while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
  // Get the conversion value
  return ADC_GetConversionValue(ADC1);
}

